import events from './events'
import MultiTab from './MultiTab'
import './index.less'

const api = {
    callbackFnMap: {}, // 回调映射表
    /**
     *
     * @param {String} key 回调函数键值，一般为路由的fullPath值
     * @param {Function} callback
     */
    registerCallback(key, callback) {
        this.callbackFnMap[key] = callback
    },
    deleteCallback(key) {
        this.callbackFnMap[key] = null
        delete this.callbackFnMap[key]
    },
    /**
     *
     * @param {String} key 回调函数键值，一般为路由的fullPath值
     * @param {Boolean} needDestroy 是否需要在回调调用后销毁
     * @return {Boolean} 返回是否成功调用的标识
     */
    invokeCallback(key, needDestroy = true) {
        if (!this.callbackFnMap[key]) return false
        this.callbackFnMap[key] && this.callbackFnMap[key]()
        if (needDestroy) {
            this.callbackFnMap[key] = null
            delete this.callbackFnMap[key]
        }
        return true
    },
    /**
     * open new tab on route fullPath
     * @param config
     */
    open: function(config) {
        events.$emit('open', config)
    },
    rename: function(key, name) {
        events.$emit('rename', { key: key, name: name })
    },
    /**
     * close current page
     */
    closeCurrentPage: function() {
        this.close()
    },
    /**
     * close route fullPath tab
     * @param config
     */
    close: function(config) {
        events.$emit('close', config)
    }
}

MultiTab.install = function(Vue) {
    if (Vue.prototype.$multiTab) {
        return
    }
    api.instance = events
    Vue.prototype.$multiTab = api
    Vue.component('multi-tab', MultiTab)
}

export default MultiTab
